package com.iflytek.crvoice2txt.database;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.iflytek.crvoice2txt.entity.RecorderEntity;
import com.iflytek.crvoice2txt.present.RecoderSignPresent;
import com.iflytek.crvoice2txt.util.DateUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmAsyncTask;
import io.realm.RealmChangeListener;
import io.realm.RealmModel;
import io.realm.RealmResults;
import io.realm.Sort;

public class RecordOperation {


    private Realm realm;

    private RecoderSignPresent.OnVoiceDictationFinished onVoiceDictationFinished;

    private OnDataChanged onDataChanged;

    public RecordOperation() {
        this.realm = Realm.getDefaultInstance();
    }

    public RecordOperation(RecoderSignPresent.OnVoiceDictationFinished onVoiceDictationFinished) {
        this.realm = Realm.getDefaultInstance();
        this.onVoiceDictationFinished = onVoiceDictationFinished;
    }

    public RecordOperation(OnDataChanged onDataChanged) {
        this.realm = Realm.getDefaultInstance();
        this.onDataChanged = onDataChanged;
    }

    public RecordOperation(RecoderSignPresent.OnVoiceDictationFinished onVoiceDictationFinished, OnDataChanged onDataChanged) {
        this.onVoiceDictationFinished = onVoiceDictationFinished;
        this.onDataChanged = onDataChanged;
    }

    public void insert(RealmModel entityType) {
        realm.beginTransaction();
        realm.copyToRealm(entityType);
        realm.commitTransaction();
    }

    public void insertAsyn(final RecorderEntity entityType) {
        RealmAsyncTask addTask = realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealm(entityType);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                if (onVoiceDictationFinished != null)
                    onVoiceDictationFinished.saveTextToDbFinished(true);
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                if (onVoiceDictationFinished != null)
                    onVoiceDictationFinished.saveTextToDbFinished(false);
            }
        });
    }

    public void updateAsyn(final RecorderEntity re, final Activity a) {
        RealmAsyncTask updateTask = realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                RecorderEntity recorderEntity = realm.where(RecorderEntity.class)
                        .equalTo("dateStr", DateUtil.DateToStr(re.date, DateUtil.DF_YYYY_MM_DD_HH_MM_SS)).findFirst();
                recorderEntity.name = re.name;
                recorderEntity.size = re.size;
                recorderEntity.type = re.type;
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                a.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(a, "保存成功！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                a.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(a, "保存失败！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public List<RecorderEntity> queryAll() {
        List<RecorderEntity> list = new ArrayList<>();
        RealmResults<RecorderEntity> recorderEntity = realm.where(RecorderEntity.class).findAll();
        recorderEntity = recorderEntity.sort("date", Sort.ASCENDING);
        list = realm.copyFromRealm(recorderEntity);
        return list;
    }

    public void queryByTimeAsyn(Date begin, Date end) {
        RealmResults<RecorderEntity> cats = realm.where(RecorderEntity.class)
                .greaterThanOrEqualTo("date", begin)
                .lessThanOrEqualTo("date", end).findAllAsync();
        cats.addChangeListener(new RealmChangeListener<RealmResults<RecorderEntity>>() {
            @Override
            public void onChange(RealmResults<RecorderEntity> element) {
                element = element.sort("date");
                List<RecorderEntity> datas = realm.copyFromRealm(element);
                if (onDataChanged != null) {
                    onDataChanged.onQueryByTimeAsyn(datas);
                }
            }
        });
    }

    public void queryAllAsyn() {
        RealmResults<RecorderEntity> cats = realm.where(RecorderEntity.class).findAllAsync();
        cats.addChangeListener(new RealmChangeListener<RealmResults<RecorderEntity>>() {
            @Override
            public void onChange(RealmResults<RecorderEntity> element) {
                element = element.sort("date");
                List<RecorderEntity> datas = realm.copyFromRealm(element);
                if (onVoiceDictationFinished != null) {
                    onVoiceDictationFinished.onQueryAllAsyn(datas);
                }
            }
        });
    }

    public void deleteRealmObject(final String date) {
        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                RecorderEntity recorderEntity = realm.where(RecorderEntity.class).equalTo("dateStr", date).findFirst();
                recorderEntity.deleteFromRealm();
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                onDataChanged.onDeleteSuccess();
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                onDataChanged.onDeleteFailed();
            }
        });
    }

    public void closeRealm() {
        if (null != realm) {
            realm.close();
        }
    }
}
